import requests
import unittest
import time
import os
from InterfaceTest.common.HTMLTestReportCN import HTMLTestRunner


# 客户端类
class Client(object):
    # 初始化参数
    def __init__(self, host, port=None):
        p = ''
        if port is not None:
            p = f':{port}'
        self.base_url = f'http://{host}{p}'
        self.session = requests.Session()

    # 项目名
    def set_project(self, project_name):
        self.base_url += project_name

    # get请求
    def get(self, path, **kwargs):
        resp = self.session.get(self.base_url + path, **kwargs)
        return resp

    # post请求
    def post(self, path, data=None, json=None, **kwargs):
        resp = self.session.post(self.base_url + path, data, json, **kwargs)
        return resp

    # 关闭session
    def close(self):
        self.session.close()


class Woniusales(unittest.TestCase):
    def setUp(self):
        """testcase每次执行之前都会去执行的"""
        self.login()

    # def tearDown(self):
    #     """testcase每次执行结束之后都会去执行"""
    #     self.logout()

    def login(self):
        path = '/user/login'
        data = {
            'username': 'admin',
            'password': 'admin123',
            'verifycode': '0000'
        }
        resp = self.client.post(path, data=data)
        self.assertEqual(200, resp.status_code)

    @classmethod
    def setUpClass(cls):
        """整个测试用例执行之前只执行一次"""
        cls.client = Client('www.woniusb.com', '8090')
        cls.client.set_project('/woniusales')

    # 编写登录的测试用例
    def test_login(self):
        """测试登录状态下访问登录页"""
        resp = self.client.get('/')
        self.assertEqual(200, resp.status_code)
        self.assertIn('蜗牛进销存-销售出库', resp.text)


if __name__ == '__main__':
    # 创建test suite
    # unittest.defaultTestloader提供了加载测试用例的方法
    # 这里我们使用loadTestsFromTestCase，根据参数加载testcase
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(Woniusales)
    # 将HTMLTestRunner运行的结果写入report.html
    with open(r'./report.html', 'wb') as f:
        # 创建HTMLTestRunner
        # verbosity: 设置为2获取更多运行信息
        # title: 标题
        # description： 描述信息
        runner = HTMLTestRunner(stream=f,
                                title='woniusales',
                                description='this is woniusales report')
        # 使用runner执行suite
        runner.run(suite)
